package com.hrserviceserve.service;

import com.hrserviceserve.dao.PersonnelRepository;
import com.hrserviceserve.dao.UserRepository;
import com.hrserviceserve.entity.ListQuery;
import com.hrserviceserve.entity.Personnel;
import com.hrserviceserve.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PersonnelService {

    @Autowired
    PersonnelRepository personnelRepository;
    @Autowired
    UserService userService;

    public Personnel findById(Integer id){
        return personnelRepository.findByPersonnelId(id);
    }
    public Personnel save(Personnel personnel1){


        Personnel personnel= personnelRepository.save(personnel1);
        User user=new User(personnel.getPersonnelName()+personnel.getPersonnelId(),String.valueOf(personnel.getPersonnelId()) ,personnel.getPosition(),null,personnel.getDepartment(),personnel.getPersonnelId());
        userService.save(user);
        return personnel;
    }
    @Transactional
    public int deleteById(Integer id){
        return personnelRepository.deleteByPersonnelId(id);
    }

    public Page findByPage(ListQuery listQuery){
        PageRequest pageRequest=PageRequest.of(listQuery.getPage()-1,listQuery.getLimit());
        Page<Personnel> allWhere = personnelRepository.
                findAllWhere(listQuery.getDepartment(), listQuery.getSex(), listQuery.getName(), pageRequest);
        return allWhere;
    }

}
